package dev.entao.travel.app

import dev.entao.base.Label
import dev.entao.base.MB
import dev.entao.base.setPropValue
import dev.entao.core.Action
import dev.entao.core.HttpApis
import dev.entao.core.HttpContext
import dev.entao.core.controllers.UploadController
import dev.entao.core.isFilePart
import dev.entao.core.render.sendResult
import dev.entao.core.slices.LoginToken
import dev.entao.core.slices.TokenSlice
import dev.entao.core.slices.tokenInfo
import dev.entao.log.logd
import dev.entao.sql.EQ
import dev.entao.sql._SQLProperties
import dev.entao.sql.nameSQL
import dev.entao.travel.model.User
import dev.entao.travel.model.jsonData
import javax.servlet.http.Part


@LoginToken("user")
@Label("用户")
class UserApi(context: HttpContext) : HttpApis(context) {
    private val currentUser: User? get() = User.one(User::id EQ context.tokenInfo.id)

    @Action
    fun upload() {
        val part: Part = context.partList.firstOrNull { it.isFilePart } ?: return context.sendResult {
            failed("没有文件")
        }
        if (part.size > 5 * MB) {
            return context.sendResult {
                failed("文件超过5M")
            }
        }
        UploadController(context).upload()
    }


    @Action
    fun info(userId: Int, uid: Int = 0) {
        val id = if (uid == 0) userId else uid
        val u = User.oneByKey(id) ?: return context.sendResult {
            failed("无此用户")
        }
        context.sendResult {
            data(u.jsonData())
        }

    }


    @Action
    fun update(key: String, value: String) {
        val allowKeys = setOf<String>(
            User::phone.nameSQL, User::identNum.nameSQL, User::portrait.nameSQL, User::nickName.nameSQL

        )
        logd("allow keys: ", allowKeys)
        if (key !in allowKeys) {
            return context.sendResult { failed("无效的属性") }
        }


        val uid = context.tokenInfo.id
        val u = User.oneByKey(uid) ?: return context.sendResult {
            failed("无此用户")
        }


        val p = User::class._SQLProperties.first { it.nameSQL == key }
        p.setPropValue(u, value)
        u.updateByKey(p)
        context.sendResult { success("已更新") }
    }


    @Action
    fun logout() {
        val uid = context.tokenInfo.id
        val type = context.tokenInfo.type
        TokenSlice.removeToken(uid, type)
        context.sendResult {
            success("已注销登录")
        }
    }


}